from math import log2

"""
请将 元素 1-10 放进堆，并展示建堆情况，及删除堆顶元素情况
    实例如下：
        建堆: [10, 9, 6, 7, 8, 2, 5, 1, 4, 3]
        删除堆顶元素： [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
"""


class Heap:
    def __init__(self, elements):
        n = len(elements)
        if n > 0:
            for root in range(2 ** int(log2(n))):
                for son in range(n - 1, root, -1):
                    if son % 2 == 0:
                        parent = son // 2 - 1
                    else:
                        parent = son // 2
                    if elements[parent] < elements[son]:
                        elements[parent], elements[son] = (
                            elements[son],
                            elements[parent],
                        )
        self.elements = elements

    def peek(self):
        return self.elements[0]

    def delete(self, element):
        self.elements.remove(element)
        Heap(self.elements)
        return element

    def insert(self, element):
        self.elements.append(element)
        Heap(self.elements)


heap = Heap([])
for i in range(10):
    heap.insert(i + 1)
print(heap.elements)
elements_deleted = []
while heap.elements != []:
    elements_deleted.append(heap.delete(heap.peek()))
print(elements_deleted)
